package com.chinasoft.dao.Impl;

import com.chinasoft.dao.CommentDAO;
import com.chinasoft.dao.UserDAO;
import com.chinasoft.entity.Comment;
import com.chinasoft.entity.User;
import com.chinasoft.utils.DbUtils;
import com.chinasoft.utils.MapToBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by YE on 2018/5/17.
 */
public class CommentDAOImpl implements CommentDAO {
    UserDAO userDAO = new UserDAOImpl();
    List<Comment> list = null;

    @Override
    public int addComment(Comment comment) {
        String sql = "insert into comment (pid,uid,cfloor,ccontent,ctime) values(?,?,?,?,?)";
        return DbUtils.update(sql, comment.getPid(), comment.getUser().getUid(), comment.getCfloor(), comment.getCcontent(),comment.getCtime());
    }

    @Override
    public int deleteComment(int cid) {
        String sql = "delete from comment where cid=?";
        return DbUtils.update(sql, cid);
    }

    @Override
    public Comment getComment(int cfloor) {
        String sql = "select * from comment where cfloor=?";
        Map map = DbUtils.getMap(sql, cfloor);
        int uid = (int) map.get("uid");
        map.remove(uid);
        User user = userDAO.selectUser(uid);
        map.put("user", user);
        return MapToBean.changeToComment(map);
    }

    @Override
    public int updateComment(Comment comment) {
        String sql = "update comment set ccontent=? where cid=?";
        return DbUtils.update(sql, comment.getCcontent(), comment.getCid());
    }

    @Override
    public int getCount(int pid) {
        String sql = "select count(*)from comment where pid=?";
        return DbUtils.getCount(sql, pid);
    }

    @Override
    public List<Comment> getAllComments(int pid,int start,int length) {
        list = new ArrayList<>();
        String sql = "select * from comment where pid=? ORDER BY cfloor ASC LIMIT ?,?";
        List<Map> li = DbUtils.getMaps(sql, pid,start,length);
        for (Map map : li) {
            int uid = (int) map.get("uid");
            map.remove(uid);
            User user = userDAO.selectUser(uid);
            map.put("user", user);
            Comment comment = MapToBean.changeToComment(map);
            list.add(comment);
        }
        return list;
    }
    @Override
    public int getCommentCount(int pid,int length) {
        list = new ArrayList<>();
        String sql = "select count(*) from comment where pid=? ORDER BY cfloor ASC";
        int len=DbUtils.getCount(sql, pid);
        if(len%length>0){
            return len/length+1;
        }
        return len/length;
    }
}
